package com.huike.springboot1.demos.security;

import com.huike.springboot1.demos.pojo.Permission;
import com.huike.springboot1.demos.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    // 权限集合，key是url，value是该url需要的权限
    private static Map<String, Collection<ConfigAttribute>> permissionMap;

    @Autowired
    private PermissionService permissionService;

    // 初始化权限映射关系
    private void loadPermissionMap() {

        permissionMap = new HashMap<>();
        // 放行路径
        ConfigAttribute permitAll = new SecurityConfig("ROLE_ANONYMOUS");
//        此处的路径下面的SecurityConfiguration通行路径缺一不可，都要通行方能真的能使用
        permissionMap.put("/toLogin", Collections.singletonList(permitAll));
        permissionMap.put("/login", Collections.singletonList(permitAll));
//        因为登录逻辑已经被security代替了。所以此处不需要也能通行，无需自己再定义，有也行
        permissionMap.put("/register", Collections.singletonList(permitAll));
        permissionMap.put("/sendCode", Collections.singletonList(permitAll));
        permissionMap.put("/doRegister", Collections.singletonList(permitAll));
        permissionMap.put("/403", Collections.singletonList(permitAll));
        permissionMap.put("/login/css/**", Collections.singletonList(permitAll));
        permissionMap.put("/login/js/**", Collections.singletonList(permitAll));
        permissionMap.put("/login/img/**", Collections.singletonList(permitAll));
        try {
            List<Permission> permissions = permissionService.getAllPermissions();
            System.out.println(">>> 成功查到权限条数：" + permissions.size());
            for (Permission p : permissions) {
                if (p.getUrl() != null && !"".equals(p.getUrl())) {
                    ConfigAttribute cfg = new SecurityConfig(p.getPermissionCode());
                    permissionMap.put(p.getUrl(), Collections.singletonList(cfg));
                    System.out.println(">>> 加载权限：" + p.getUrl() + " -> " + p.getPermissionCode());
                }
            }
            System.out.println(">>> 权限Map加载完成，共 " + permissionMap.size() + " 条URL规则");
        } catch (Exception e) {
            System.out.println(">>> 权限查询失败，原因：" + e.getClass().getSimpleName() + " - " + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        // 获取当前请求
        HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
        //把这行放在最前面
        System.out.println(">>> getAttributes 被调用，URL=" + request.getRequestURI());
        // 如果权限映射为空，则加载
        if (permissionMap == null) {
            loadPermissionMap();
        }

        // 匹配请求路径对应的权限
        for (String url : permissionMap.keySet()) {
            AntPathRequestMatcher matcher = new AntPathRequestMatcher(url);
            if (matcher.matches(request)) {
                return permissionMap.get(url);
            }
        }

        // 如果没有匹配到的url，默认需要登录
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
